package com.nova.bluetooth.ui.device;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;

import android.app.ProgressDialog;
import android.bluetooth.BluetoothGatt;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.dido.fastblelib.data.BleDevice;
import com.dido.fastblelib.exception.BleException;
import com.nova.bluetooth.adapter.ScanningAdapter;
import com.nova.bluetooth.bean.DeviceConfigBean;
import com.nova.bluetooth.databinding.ActivityAppScanBluetoothBinding;
import com.nova.bluetooth.helpUtils.MyGattCallback;
import com.nova.bluetooth.helpUtils.MyScanCallback;
import com.nova.bluetooth.helpUtils.ToastUtils;
import com.nova.bluetooth.manage.BluetoothHelper;
import com.nova.bluetooth.permission.OnPermissionListener;
import com.nova.bluetooth.permission.PermissionManageActivity;
import com.nova.bluetooth.permission.PermissionType;

import java.util.List;

public class AppScanBluetoothActivity extends PermissionManageActivity implements MyScanCallback, MyGattCallback {

    private ActivityAppScanBluetoothBinding binding;
    private DeviceConfigBean deviceConfigBean;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        binding = ActivityAppScanBluetoothBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
        initData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        BluetoothHelper.getInstance().cancelScan();
        BluetoothHelper.getInstance().cleanCallback();
    }

    private ScanningAdapter mAdapter;

    private ProgressDialog progressDialog;


    private void showProgressDialog() {
        // 显示 ProgressDialog
        if (!progressDialog.isShowing()) {
            progressDialog.show();
        }
    }

    private void dismissProgressDialog() {
        // 隐藏 ProgressDialog
        if (progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
    private void initView() {
        mAdapter = new ScanningAdapter();
        binding.recycler.setLayoutManager(new LinearLayoutManager(this));
        binding.recycler.setAdapter(mAdapter);

        binding.ivBack.setOnClickListener(v -> finish());
        binding.btnScan.setOnClickListener(v -> {
            mAdapter.getData().clear();
            goScanBle();
        });

        mAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                BluetoothHelper.getInstance().connect(mAdapter.getData().get(position));
            }
        });

        // 初始化 ProgressDialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在连接设备...");
        progressDialog.setCancelable(false);

        // 创建一个旋转动画，从0度旋转到360度，围绕中心点旋转
        rotateAnimation = new RotateAnimation(0, 360,
                Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rotateAnimation.setDuration(1000); // 设置动画持续时间为1秒
        rotateAnimation.setRepeatCount(Animation.INFINITE); // 设置动画无限循环


    }

    private void initData() {
//        List<String > mData = new ArrayList<>();
//        for (int i = 0; i < 5; i++){
//            mData.add("devices"+ i);
//        }
//        mAdapter.setList(mData);

        BluetoothHelper.getInstance().setScanCallback(this);
        BluetoothHelper.getInstance().setGattCallback(this);
        goScanBle();
    }


    private RotateAnimation rotateAnimation;
    public void startRotation() {
        if (rotateAnimation != null) {
            binding.ivScanning.startAnimation(rotateAnimation);
        }
    }

    public void stopRotation() {
        if (rotateAnimation != null) {
            binding.ivScanning.clearAnimation();
        }
    }

    private void goScanBle() {
//        if (deviceConfigBean == null) {
//            LogUtil.e(TAG + " deviceName is null");
//            return;
//        }

        getBluetoothPermission(new OnPermissionListener() {
            @Override
            public void onPermissionGranted(PermissionType permissionType) {
                BluetoothHelper.getInstance().startScanAll();
            }

            @Override
            public void onPermissionDenied(PermissionType permissionType) {

            }
        }, "获取蓝牙设备需要定位、发现附近设备权限");
    }



    @Override
    public void onStartConnect() {
        showProgressDialog();
    }

    @Override
    public void onConnectFail(BleDevice bleDevice, BleException exception) {
        dismissProgressDialog();
        ToastUtils.show("连接失败:" + exception.toString());
    }

    @Override
    public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
        ToastUtils.show("蓝牙连接成功，正在建立通信:" + bleDevice.getName());
        dismissProgressDialog();
//        finish();
    }

    @Override
    public void onDisConnected(boolean isActiveDisConnected, BleDevice bleDevice, BluetoothGatt gatt, int status) {
        ToastUtils.show("蓝牙连接断开:" + bleDevice.getName());
        dismissProgressDialog();
    }

    @Override
    public void onConnectedNotifySuccess(BleDevice bleDevice) {
        ToastUtils.show("数据通信已打开:" + bleDevice.getName());
        dismissProgressDialog();
        finish();
    }

    @Override
    public void onScanStarted() {
        binding.btnScan.setText("开始扫描");
        binding.btnScan.setClickable(false);
        binding.btnScan.setVisibility(GONE);
        startRotation();
    }

    @Override
    public void onScanning(BleDevice bleDevice) {
        if (bleDevice.getName() != null){
            mAdapter.addData(bleDevice);
        }
        binding.tvScanTips.setText("扫描中...");
        binding.recycler.setVisibility(VISIBLE);
        binding.tvScanTips.setVisibility(VISIBLE);
    }

    @Override
    public void onScanFinished(List<BleDevice> scanResultList) {
        binding.btnScan.setText("重新扫描");
        binding.tvScanTips.setText("扫描完毕");
        binding.btnScan.setClickable(true);
        binding.btnScan.setVisibility(VISIBLE);
        stopRotation();
    }
}